package cn.neusoft.yp.controller;

import cn.neusoft.yp.pojo.User;
import cn.neusoft.yp.service.UserService;
import cn.neusoft.yp.tool.IsNullUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by gaosheng on 2017/4/27.
 */
@Controller
public class UserController extends BaseController {

    @Autowired
    private UserService userService ;

    /**
     * 首页
     * @return
     */
    @RequestMapping("home")
    public String home(){
        return "index" ;
    }


    /**
     * 跳转到注册页
     * @return
     */
    @RequestMapping("regist")
    public String regist(){
        return "regist" ;
    }

    /**
     * 用户注册
     * @param user 注册的用户对象
     * @return 返回到用户列表页面
     */
    @RequestMapping("save")
    public String saveUser(@Validated User user, BindingResult bindingResult, Model model){
       if(IsNullUtils.isNull(user.getUsername())) {
            model.addAttribute("errorInfo", "用户名不能为空");
            return "regist";
        }else if(IsNullUtils.isNull(user.getPassword())){
            model.addAttribute("errorInfo", "密码不能为空");
            return "regist";
        }else  if(IsNullUtils.isNull(user.getPassword2())){
            model.addAttribute("errorInfo", "确认密码不能为空");
            return "regist";
        }else  if(IsNullUtils.isNull(user.getNickname())){
            model.addAttribute("errorInfo", "昵称不能为空");
            return "regist";
        }else  if(IsNullUtils.isNull(user.getEmail())){
            model.addAttribute("errorInfo", "邮箱不能为空");
            return "regist";
        }else  if(!user.getPassword().equals(user.getPassword2())){
            model.addAttribute("errorInfo", "两次输入密码不一致");
            return "regist";
        }else  if(!user.getEmail().matches("^\\w+@\\w+(\\.\\w+)+$")){
            model.addAttribute("errorInfo", "邮箱格式不正确");
            return "regist";
        }else {
            userService.saveUser(user);
            return "index";
        }
    }

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping("login")
    public String login(){
        return "login" ;
    }


    //登录校验
    @RequestMapping("loginSave")
    public String login(Model model, String username, String password, String remname, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

       //校验用户名和密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            String errorInfo = "用户名或密码不能为空";
            model.addAttribute("errorInfo", errorInfo);
            return "login";
        }
        // >>记住用户名
        if ("true".equals(remname)) {
            Cookie cookie = new Cookie("remname",
                    URLEncoder.encode(username,
                            "utf-8"));
            cookie.setPath(request.getContextPath()
                    + "/");
            cookie.setMaxAge(60 * 60 * 24 * 30);
            response.addCookie(cookie);
        } else { // 取消记住用户名(直接删除名为remname的cookie)
            Cookie cookie = new Cookie("remname", "");
            cookie.setPath(request.getContextPath()+ "/");
            cookie.setMaxAge(0);
            response.addCookie(cookie);
        }
        /**
         * 1.将用户名和密码封装到toKen（令牌）中
         * 2.将准备好的toKen通过subject进行提交
         * 3.处理提交后的结果 进行正确的转向
         */
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //生成subject用户
        Subject subject = SecurityUtils.getSubject();
        //进行登录  登录结果如果不正确则抛出异常
        try {
            subject.login(token);
            User user = (User) subject.getPrincipal();//获取真实的用户对象
            subject.getSession().setAttribute("user_session", user);
            //用户名和密码正确
            return "index";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            model.addAttribute("errorInfo", "用户名或密码错误");
            return "login";
        }
    }

    @RequestMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute("user_session");
        return "index";
    }
}
